const mongoose = require('mongoose')
const boom = require('boom')
const fs = require('fs')

const User = require('../models/user')

const environment = process.env.NODE_ENV
const stage = require('../config')[environment]

module.exports = {
  create: (req, res, next) => {
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 201
        const {
          username,
          password
        } = req.body
        const user = new User({
          username,
          password
        })
        user.save((err, user) => {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          result.status = status
          result.data = user
          mongoose.connection.close()
          return res.status(status).send(result)
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  },
  delete: (req, res, next) => {
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 200
        const {
          id
        } = req.params
        User.findByIdAndDelete(id).
        exec(function (err, user) {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          result.status = status
          result.data = user
          mongoose.connection.close()
          return res.status(status).send(result)
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  },
  update: (req, res, next) => {
    const err = validationResult(req)
    if (!err.isEmpty()) {
      const [{
        msg
      }] = err.errors
      return next(boom.badRequest(msg))
    }
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 200
        let avatar = ''
        const {
          id
        } = req.params
        if (req.file) {
          const {
            destination: des, // 文件本地存储目录
            filename, // 文件名称
            path,
            mimetype // 文件资源类型
          } = req.file
          const suffix = mimetype.split('/')[1]
          const file_path = `${des}/${filename}.${suffix}`
          if (fs.existsSync(path) && !fs.existsSync(file_path)) {
            fs.renameSync(path, file_path) // 重命名文件
          }
          avatar = `/user/${filename}${suffix}` // 用户头像文件路径
        }
        User.findByIdAndUpdate(id, {
          'avatar': avatar
        }).
        exec(function (err, user) {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          result.status = status
          result.data = user
          mongoose.connection.close()
          return res.status(status).send(result)
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  },
  show: (req, res, next) => {
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 200
        const {
          id
        } = req.params
        User.findById(id).
        exec(function (err, user) {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          result.status = status
          result.data = user
          mongoose.connection.close()
          return res.status(status).send(result)
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  },
  index: (req, res, next) => {
    mongoose.connect(process.env.MONGOLAB_URI, stage.mongo_options).then(
      () => {
        let result = {}
        let status = 200
        let {
          pagesize = 20, page = 1
        } = req.query
        pagesize = Number(pagesize)
        page = Number(page)
        const num = (page - 1) * pagesize
        const condition = {}
        User.find(condition).
        skip(num).
        limit(pagesize).
        exec(function (err, users) {
          if (err) {
            mongoose.connection.close()
            return next(boom.badImplementation(err))
          }
          result.status = status
          result.data = users
          mongoose.connection.close()
          return res.status(status).send(result)
        })
      },
      err => {
        mongoose.connection.close()
        return next(boom.badImplementation(err))
      }
    )
  }
}
